param([string]$serviceName = "");

### BEGIN SELF-ELEVATION ###

# Get the ID and security principal of the current user account

$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running "as Administrator"
if (-Not $myWindowsPrincipal.IsInRole($adminRole))
{
	$arguments = "& '" + $myinvocation.mycommand.definition + "'"
	Start-Process powershell -Verb runAs -ArgumentList $arguments
	exit;
}

### END SELF-ELEVATION ###

# Define Names
$plist_path = $PSScriptRoot + "\..\Info.plist"
Write-Host $plist_path

[xml]$InfoPlist = Get-Content -Path $plist_path;
$appName = $InfoPlist.SelectSingleNode("//key[text()='CFBundleDisplayName']").get_nextsibling()."#text";
Write-Host "appName is " $appName;


if($serviceName -eq "")
{
	$serviceName = "VSS " + $appName;
}

# Define Folders
$VSSAppdataFolder  = $env:ALLUSERSPROFILE + "\" + $appName + "\VSS\";
$VSSResourceFolder = $PSScriptRoot + "\";

$ResourceBinaryPath = $VSSResourceFolder + "vss_writer.exe";
$AppDataBinaryPath = $VSSAppdataFolder + "VSS " + $appName + ".exe";

# Does the service Exist at all ?
if ($serviceObj = Get-Service $serviceName -ErrorAction SilentlyContinue)
{
	# Is it Running ?
	if( ($serviceObj | select -expand "status") -eq "running" )
	{
		Write-Host "Stopping Service " $serviceName;
		Stop-Service $serviceName;
		Get-Service -Name $serviceName | % { $_.WaitForStatus([System.ServiceProcess.ServiceControllerStatus]::Stopped, "00:01:00") };
	}

	Write-Host "Deleting Service " $serviceName;
    sc.exe delete $serviceName;

	start-sleep -seconds 1;
	Write-Host "waiting for service to be deleted. Please close any SC manager if open";

	$timeout = new-timespan -Minutes 1;
	$sw = [diagnostics.stopwatch]::StartNew();
	while ( ($sw.elapsed -lt $timeout) -And (Get-Service $serviceName -ErrorAction SilentlyContinue) )
	{
		start-sleep -seconds 1;
	}

	if (Get-Service $serviceName -ErrorAction SilentlyContinue)
	{
			Write-Host "Failed to delete Service";
			exit;
	}
}

# delete the %appdata% directory
Write-Host "removing " $VSSAppdataFolder;
Remove-Item -Recurse -Force $VSSAppdataFolder;

# Recreate it
New-Item $VSSAppdataFolder -type directory;

# copy the directory to %appdata%
Write-Host "Updating from " $VSSResourceFolder ;
Copy-Item $ResourceBinaryPath $AppDataBinaryPath;
Copy-Item ($VSSResourceFolder + "vss.plist") ($VSSAppdataFolder + "vss.plist");

$root_path = $VSSResourceFolder + "/../../"

$dll_source = ""
$dll_target = ""

if( (Test-Path ($root_path + "msvcr120d.dll")) -And (Test-Path ($root_path + "msvcp120d.dll")))
{
	$dll_source = $root_path + "msvcr120d.dll"
	$dll_target = $VSSAppdataFolder + "msvcr120d.dll"
	Copy-Item $dll_source $dll_target;

	$dll_source = $root_path + "msvcp120d.dll"
	$dll_target = $VSSAppdataFolder + "msvcp120d.dll"
	Copy-Item $dll_source $dll_target;
}
ElseIf((Test-Path ($root_path + "msvcr120.dll")) -And (Test-Path ($root_path + "msvcp120.dll")))
{
	$dll_source = $root_path + "msvcr120.dll"
	$dll_target = $VSSAppdataFolder + "msvcr120.dll"
	Copy-Item $dll_source $dll_target;

	$dll_source = $root_path + "msvcp120.dll"
	$dll_target = $VSSAppdataFolder + "msvcp120.dll"
	Copy-Item $dll_source $dll_target;

}


New-Service -name $serviceName -binaryPathName $AppDataBinaryPath -displayName $serviceName -startupType Automatic ;
Start-Service -name $serviceName;

# this line is useless in many cases, but If this script as non admin is launched from a xxx.cmd using:
# > powershell -executionPolicy bypass -file "%~dp0\InstallService.ps1"
# This lines fire and event VSSIsInstalled which the script can wait for using "waitfor /t 60 VSSIsInstalled " for instance...
waitfor /si VSSIsInstalled

# DEBUG LINES... If you want not to exit after completion
# Read-Host -Prompt "Press Enter to continue"
# Note $host.UI.RawUI.ReadKey will not work inside powershell ISE...
exit;
